package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.domain.*;
import cn.wolfcode.luowowo.article.service.*;
import cn.wolfcode.luowowo.cache.service.IAttractionStatisRedisService;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisRedisService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisRedisService;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.comment.domain.AttractionComment;
import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.service.IAttractionCommentService;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.comment.vo.AttractionCommentVo;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/mine")
public class MineController {

    @Reference
    private ITravelService travelService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IUserInfoService userInfoService;
    @Reference
    private IUserInfoRedisService userInfoRedisService;
    @Reference
    private IAttractionService attractionService;
    @Reference
    private IAttractionStatisRedisService attractionStatisRedisService;
    @Reference
    private IStrategyStatisRedisService strategyStatisRedisService;
    @Reference
    private IStrategyCommentService strategyCommentService;
    @Reference
    private ITravelStatisRedisService travelStatisRedisService;
    @Reference
    private ITravelCommentService travelCommentService;
    @Reference
    private IAttractionCommentService attractionCommentService;
    @Reference
    private IUserCommodityService userCommodityService;
    @Reference
    private ICommodityService commodityService;
    @Reference
    private IUserGoldService userGoldService;

    /**
     *
     * 我的窝
     *
     * @param model
     * @param userInfo
     * @return
     */
    @RequireLogin
    @RequestMapping("/home")
    public String home(Model model, @UserParam UserInfo userInfo){
        List<Travel> list = travelService.getMyTravelByUserId(userInfo.getId());
        model.addAttribute("list",list);
        model.addAttribute("size",list.size());
        //点评
        List<AttractionComment> acs = attractionCommentService.getByUserId(userInfo.getId());
        ArrayList<AttractionComment> acList = new ArrayList<>();
        AttractionCommentVo vo = new AttractionCommentVo();
        for (AttractionComment ac : acs) {
            AttractionComment att = new AttractionComment();
            try {
                BeanUtils.copyProperties(att,ac);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            for (Map<String, Object> map : ac.getReplay()) {
                att.setRelynum(att.getRelynum()+1);
            }
            vo.setAttnum(vo.getAttnum()+1);
            acList.add(att);
        }
        model.addAttribute("acs",acList);
        model.addAttribute("vo",vo);
        return "personal/homepage";
    }

    /**
     *
     * 我的游记
     *
     * @param model
     * @param userInfo
     * @return
     */
    @RequireLogin
    @RequestMapping("/mytravelnotes")
    public String mytravelnotes(Model model,@UserParam UserInfo userInfo){
        List<Travel> list = travelService.getMyTravelByUserId(userInfo.getId());
        model.addAttribute("list",list);
        model.addAttribute("size",list.size());
        Integer replynum = 0;
        Integer viewnum = 0;
        for (Travel travel : list) {
            replynum = replynum + travel.getReplynum();
            viewnum = viewnum + travel.getViewnum();
        }
        model.addAttribute("replynum",replynum);
        model.addAttribute("viewnum",viewnum);
        return "personal/mytravelnotes";
    }


    /**
     * 设置
     * @param model
     * @param userInfo
     * @return
     */
    @RequireLogin
    @RequestMapping("/setting")
    public String setting(Model model, @UserParam UserInfo userInfo){
        Destination dest = destinationService.selectByDestName(userInfo.getCity());
        model.addAttribute("dest",dest);
        //蜂蜜余额
        model.addAttribute("userGold",userGoldService.selectByUserId(userInfo.getId()));
        List<UserCommodity> userCommodities = userCommodityService.selectParticularsByUserId(userInfo.getId());
        model.addAttribute("ucs",userCommodities);
        return "personal/setting";
    }

    /**
     *
     *修改我的信息
     *
     * @param gserInfo
     * @param userInfo
     * @param request
     * @param response
     * @return
     */
    @RequireLogin
    @RequestMapping("/updateMyMessage")
    public String updateMyMessage(UserInfo gserInfo, @UserParam UserInfo userInfo, HttpServletRequest request, HttpServletResponse response){
        gserInfo.setId(userInfo.getId());
        userInfoService.updateById(gserInfo);
        String token = userInfoService.getUser(userInfo.getPhone());
        CookieUtil.addCookie(response,"token",token, RedisKeys.USER_LOGIN.getTime().intValue());
        String userStr = userInfoRedisService.getToken(token);
        UserInfo user = JSON.parseObject(userStr, UserInfo.class);
        request.getSession().setAttribute("userInfo",user);
        return "redirect:/mine/home";
    }

    /**
     *
     * 点评
     *
     * @return
     */
    @RequireLogin
    @RequestMapping("/review")
    public String review(@UserParam UserInfo userInfo,Model model){
        List<AttractionComment> acs = attractionCommentService.getByUserId(userInfo.getId());
        ArrayList<AttractionComment> acList = new ArrayList<>();
        AttractionCommentVo vo = new AttractionCommentVo();
        for (AttractionComment ac : acs) {
            AttractionComment att = new AttractionComment();
            try {
                BeanUtils.copyProperties(att,ac);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            List<String> commentUrl = ac.getCommentUrl();
            String s = commentUrl.get(0);
            System.out.println(s);
            //System.out.println(ac.getContent());
            att.setFirstCommentUrl(s);
            System.out.println("!!!!" + att.getCommentUrl());
            vo.setAttnum(vo.getAttnum()+1);
            acList.add(att);
        }
        model.addAttribute("acs",acList);
        model.addAttribute("vo",vo);
        return "personal/review";
    }

    /**
     * 收藏
     * @param userInfo
     * @param model
     * @return
     */
    @RequireLogin
    @RequestMapping("travelcollection")
    public String travelcollection(@UserParam UserInfo userInfo,Model model) throws Exception {
        //查询出当前用户收藏的景点
        List<Attraction> atts = attractionStatisRedisService.getAttractionByUserId(userInfo.getId());
        for (Attraction att : atts) {
            att.setCoverUrl(att.getCoverUrlList().subList(0,1).get(0));
        }
        model.addAttribute("atts",atts);
        //查询出当前用户收藏的所有的攻略
        List<StrategyDetail> stds = strategyStatisRedisService.getStrategyDetailByUserId(userInfo.getId());
        List<StrategyDetail> strates = new ArrayList<>();
        for (StrategyDetail std : stds) {
            System.out.println(std.getAuthor().getId());
            StrategyDetail strategyDetail = new StrategyDetail();
            BeanUtils.copyProperties(strategyDetail,std);
            //查询出最新评论的人
            StrategyComment newComment = strategyCommentService.getByNewTime(std.getId());
            strategyDetail.setStrategyComment(newComment);
            strates.add(strategyDetail);
        }
        model.addAttribute("stds",strates);
        //游记收藏
        List<Travel> travels = travelStatisRedisService.getTravelByUserId(userInfo.getId());
        List<Travel> travelss = new ArrayList<>();
        for (Travel travel : travels) {
            System.out.println(travel.getAuthor().getId());
            Travel tra = new Travel();
            BeanUtils.copyProperties(tra,travel);
            //查询出最新评论的人
            TravelComment newComment = travelCommentService.getByNewTime(travel.getId());

            tra.setTravelComment(newComment);
            //System.out.println("=======>" + tra.getCoverUrl());
            travelss.add(tra);
        }
        model.addAttribute("travels",travelss);
        return "personal/travelcollection";
    }

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @RequestMapping("/sendPhoneVerifyCode")
    @ResponseBody
    public Object sendVerifyCodeByUpdate(String phone){
        userInfoService.sendVerifyCode(phone);
        return AjaxResult.SUCCESS;
    }
    /**
     * 发送新的手机的验证码
     * @param newMobile
     * @return
     */
    @RequestMapping("/sendNewPhoneVerifyCode")
    @ResponseBody
    public Object sendNewPhoneVerifyCode(String newMobile){
        userInfoService.sendVerifyCode(newMobile);
        return AjaxResult.SUCCESS;
    }

    /**
     * 验证验证码是否正确
     *
     * @param phone
     * @return
     */
    @RequestMapping("/checkVerifyCode")
    @ResponseBody
    public Object checkVerifyCode(String phone, String code){
        String key = RedisKeys.VERIFY_CODE.join(phone);
        String windowCode = userInfoRedisService.getVerifyCode(key);
        System.out.println(windowCode);
        if (windowCode == null || !windowCode.equalsIgnoreCase(code)) {
            throw new LogicException("验证码失效或错误");
        }
        return AjaxResult.SUCCESS;
    }

    /**
     * 验证新的验证码是否正确
     * 然后就是修改该手机号了
     *
     * @param
     * @return
     */
    @RequestMapping("/setNewPhone")
    @ResponseBody
    public Object setNewPhone(String newMobile, String verifyCode,@UserParam UserInfo userInfo){
        String key = RedisKeys.VERIFY_CODE.join(newMobile);
        String windowCode = userInfoRedisService.getVerifyCode(key);
        System.out.println(newMobile);
        System.out.println(windowCode);
        if (windowCode == null || !windowCode.equalsIgnoreCase(verifyCode)) {
            throw new LogicException("验证码失效或错误");
        }
        if (newMobile.equals(userInfo.getPhone())){
            throw new LogicException("新手机号与旧手机号重复了");
        }
        //userInfoService.updatePhone(userInfo.getPhone(),newMobile);
        userInfoService.updatePhone(userInfo.getPhone(),newMobile);
        return AjaxResult.SUCCESS;
    }


    /**
     * 我的订单
     */
    @RequestMapping("/myOrder")
    public String order(){

        return "/personal/order";
    }

    @RequestMapping("/deleteFavor")
    @ResponseBody
    public Object deleteFavor(Long id){
        System.out.println(id);
        travelStatisRedisService.removeFavor(id);
        return AjaxResult.SUCCESS;
    }
}
